<?php
namespace app\controller;

class ApiController extends BaseController
{
    /*
    * 接口列表
    */
    public function index()
    {
        if(!session("member_id")){
            return redirect(url('Account/login'));
        }
        $this->sitedb->map=[];
        $this->sitedb->map_eq("id",input('project_id'));
        $data['project_info']=$this->sitedb->find("project");

        $this->sitedb->map=[];
        $this->sitedb->map_eq('project_id',$data['project_info']['id']);
        $this->sitedb->order_asc("sort");
        $this->sitedb->order_asc("id");
        $api_list=$this->sitedb->select("project_api");

        $api_data=[];
        foreach ($api_list as $v){
            if($v['pid']!=0) continue;
            foreach ($api_list as $row){
                if($v['id']!=$row['pid']) continue;
                $v['_child'][]=$row;
            }
            $api_data[$v['id']]=$v;
        }
        $data['list']=array_values($api_data);
		return view('', $data);
    }
    /*
    * 非登录用户访问接口列表
    */
    public function external(){
        $this->sitedb->map=[];
        $this->sitedb->map_eq("unique_code",input('unique_code'));
        $data['project_info']=$this->sitedb->find("project");

        $this->sitedb->map=[];
        $this->sitedb->map_eq('project_id',$data['project_info']['id']);
        $this->sitedb->order_asc("sort");
        $this->sitedb->order_asc("id");
        $data['list']=$this->sitedb->select("project_api")->toArray();

        return view('',$data);
    }

    /*
    * 模块名称修改
    */
    public function module(){
        if(request()->isPost()){
            if(!session("member_id")){
                return redirect(url('Account/login'));
            }
            $data['title']=input('module_title');
            $data['project_id']=input('project_id');
            if(input('id')){
                $this->sitedb->map_eq("id",input("id"));
            }
            /* 验证 -S */
            $validate=new \app\validate\Module;
            $check_result=$validate->check($data);
            if(!$check_result){
                return $this->error($validate->getError());
            }
            /* 验证 -E */
            $this->sitedb->data=$data;
            $result=$this->sitedb->update("project_api");
            return $this->success("保存成功");
        }else{

        }
    }
    /*
    * 删除模块
    */
    public function delModule(){
        if(!session("member_id")){
            return redirect(url('Account/login'));
        }
        if(!input("module_id")){
            return $this->error("模块ID异常");
        }
        $this->sitedb->map=[];
        $this->sitedb->map_eq("id",input('module_id'));
        $module_info=$this->sitedb->find("project_api");
        $this->sitedb->map=[];
        $this->sitedb->map_eq("id",$module_info['project_id']);
        $project_info=$this->sitedb->find("project");
        if($project_info['member_id']!=session("member_id")){
            return $this->error("只能删除自己项目下的模块");
        }
        $this->sitedb->map=[];
        $this->sitedb->mapOr=[
            ["id","=",input('module_id')],
            ['pid',"=",input('module_id')]
        ];
        $this->sitedb->delete_data("project_api");
        return $this->success("删除成功");
    }
    //添加项目
    public function add(){
        if(request()->isPost()){
            return $this->update();
        }else{
            return $this->operate();
        }
    }
    //修改项目
    public function edit(){
        if(request()->isPost()){
            return $this->update();
        }else{
            return $this->operate();
        }
    }
    //通用项目编辑展示方法
    private function operate(){
        if(!session("member_id")){
        //    return redirect(url('Account/login'));
        }
        if(!input("project_id") && !input("ids")){
            return $this->error("项目ID异常");
        }
        $data['info']=null;
        $data['api_info']=[];
        if(input("project_id")) {
            $this->sitedb->map = [];
            $this->sitedb->map_eq("id", input('project_id'));
            $project_info = $this->sitedb->find("project");
        }else if(input("ids")){
            $this->sitedb->map=[];
            $this->sitedb->map_eq("id",input('ids'));
            $data['info']=$this->sitedb->find("project_api");
            $data['api_info']=json_decode($data['info']['api_param'],true);

            $this->sitedb->map = [];
            $this->sitedb->map_eq("id",$data['info']['project_id']);
            $project_info = $this->sitedb->find("project");
        }
        $data['project_info']=$project_info;
        $this->sitedb->map=[];
        $this->sitedb->map_eq("project_id",$project_info['id']);
        $this->sitedb->map_eq("pid",0);
        $data['module_list']=$this->sitedb->select("project_api");
        return view('operate',$data);

    }
    //通用项目编辑提交方法
    private function update(){
        if(!session("member_id")){
            return redirect(url('Account/login'));
        }
        $data=input("post.");
        if(input('id')){
            $this->sitedb->map_eq("id",input("id"));
        }else{
            $data['serial_num'] = date('YmdHis');
            $data['member_id'] = session('member_id');
        }
        $api_param=[];
        if(isset($data['api_param'])) {
            foreach ($data['api_param']['name'] as $key => $val) {
                $api_param_val = null;
                $api_param_val['name'] = $val;
                $api_param_val['type'] = $data['api_param']['type'][$key];
                $api_param_val['is_require'] = $data['api_param']['is_require'][$key];
                $api_param_val['default'] = $data['api_param']['default'][$key];
                $api_param_val['remark'] = $data['api_param']['remark'][$key];
                $api_param_val['demo'] = $data['api_param']['demo'][$key];
                $api_param[] = $api_param_val;
            }
        }
        $data['api_param'] = json_encode($api_param);

        /* 验证 -S */
        $validate=new \app\validate\Api;
        $check_result=$validate->check($data);
        if(!$check_result){
            return $this->error($validate->getError());
        }
        /* 验证 -E */
        $this->sitedb->data=$data;
        $result = $this->sitedb->update("project_api");
        if(is_numeric($result)){
            return $this->success('操作成功','',url('Api/index',['project_id'=>$data['project_id']]));
        }else{
            return $this->error($result);
        }
    }

    /**
     * 复制接口
     */
    public function copy(){
        if(!session("member_id")){
            return redirect(url('Account/login'));
        }
        if(intval(input('ids'))==0){
            return $this->error("复制失败");
        }
        $this->sitedb->map_eq("id",input('ids'));
        $this->sitedb->field='project_id,pid,title,api_url,remark,request_type,api_param,return_param';
        $api_info=$this->sitedb->find('project_api');

        $this->checkProjectMember($api_info['project_id']);

        $data=$api_info;
        $data['title']=$api_info['title'].'_copy';
        $data['serial_num'] = date('YmdHis');
        $data['member_id'] = session('member_id');
        $this->sitedb->map=[];
        $this->sitedb->data=$data;
        $result = $this->sitedb->update("project_api");
        if(is_numeric($result)){
            return $this->success('复制成功','',url("Api/index",['project_id'=>$api_info['project_id']]));
        }else{
            return $this->error($result);
        }
    }
    /*
    * 改变接口顺序
    */
    public function changeSort(){
        $api_ids=explode(",",input("api_ids"));
        $data=[];
        for($num=count($api_ids);$num>0;$num--){
            $data[]=['id'=>$api_ids[$num-1],'sort'=>$num];
            $this->sitedb->map=[];
            $this->sitedb->map_eq("id",$api_ids[$num-1]);
            $this->sitedb->data=[
                'sort'=>$num
            ];
            $this->sitedb->update("project_api");
        }
        return $this->success('调整成功');
    }
    /*
    * 删除项目
    */
    public function del(){
        $this->sitedb->map=[];
        $this->sitedb->map_eq("id",input('ids'));
        $this->sitedb->field="project_id";
        $api_info=$this->sitedb->find("project_api");

        $this->checkProjectMember($api_info['project_id']);

        $this->sitedb->map=[];
        $this->sitedb->map_eq("id",input("ids"));
        $this->sitedb->delete_data("project_api");
        return $this->success('删除成功','',url('Api/index',array('project_id'=>$api_info['project_id'])));
    }
    /*
    * 检查项目权限
    */
    private function checkProjectMember($project_id){
        $this->sitedb->map=[];
        $this->sitedb->map_eq("id",$project_id);
        $this->sitedb->field="member_id";
        $project_info=$this->sitedb->find("project");

        $project_member=$this->sitedb->column("project_member","project_id","member_id");
        $project_member_ids=array_keys($project_member);
        $project_member_ids[]=$project_info['member_id'];
        if(!in_array(session("member_id"),$project_member_ids)){
            return $this->error("只能对自己创建或参与的项目进行操作");
        }
    }
}
